﻿using System;
using System.Collections;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;

namespace TienTeTuong
{
    public class Common
    {
        ///
        public static int iNumItemPerPage;

        public static int iNumHotItemPerPage;
        public static int numItemArticlePerPage = 10;
        public static int numTopHotProductDetail = 5;
        public static int numTopArticle = 5;

        /// <summary>
        ///     check input string isnumber
        /// </summary>
        /// <param name="strNumber"></param>
        /// <returns></returns>
        public static bool IsNumber(String strNumber)
        {
            if (string.IsNullOrEmpty(strNumber))
                return false;
            var objNotWholePattern = new Regex("[^0-9]");
            return !objNotWholePattern.IsMatch(strNumber);
        }

        /// <summary>
        ///     ham xu li hien thi chuoi voi so ki tu mong muon, neu vuot qua thi hien thi ...
        /// </summary>
        /// <param name="strURL"></param>
        /// <param name="numChar"></param>
        /// <returns></returns>
        public static string SplitString(string strURL, int numChar)
        {
            string strReturn;
            if (string.IsNullOrEmpty(strURL))
            {
                return "...";
            }
            int lenght = strURL.Length;
            if (lenght >= numChar)
            {
                strReturn = strURL.Substring(0, numChar);
                strReturn += "...";
            }
            else
            {
                strReturn = strURL;
            }
            return strReturn.Trim();
        }

        public static string SplitContentArticle(string content, int numChar)
        {
            string strReturn = "";
            if (string.IsNullOrEmpty(content))
            {
                return "...";
            }
            int lenght = content.Length;
            if (lenght >= numChar)
            {
                strReturn = content.Substring(0, numChar);
                int lastWhiteSpace = strReturn.LastIndexOf(" ", StringComparison.Ordinal);
                strReturn = strReturn.Substring(0, lastWhiteSpace);
                strReturn += "...";
            }
            else
            {
                strReturn = content;
            }
            return strReturn.Trim();
        }

        public static void CalculateBoundry(int maximumPages, int totalPages, int currentPage, out int lowerBound,
                                            out int upperBound)
        {
            //if (totalPages < maximumPages)
            if (totalPages <= maximumPages)
            {
                lowerBound = 1;
                upperBound = totalPages;
            }
            else
            {
                // NOTE: Look in to saturated arithmetic
                int rightDisplay = maximumPages/2;
                int leftDisplay = maximumPages - rightDisplay;
                lowerBound = currentPage - leftDisplay;
                int lowerOffset = 0 - lowerBound;

                upperBound = currentPage + (rightDisplay) + (lowerOffset > 0 ? lowerOffset : 0);
                int upperOffset = upperBound > totalPages ? upperBound - totalPages : 0;
                upperBound = (totalPages - upperBound) > 0 ? upperBound : totalPages;

                lowerBound = (lowerBound > 0
                                  ? (lowerBound + lowerBound > upperOffset ? lowerBound - upperOffset : 0)
                                  : 1);
                if (lowerBound == 0) lowerBound = 1;

                if (lowerBound == 1) upperBound = 5;
            }
        }

        /// <summary>
        ///     CHuyen tieng Viet co dau sang tieng Viet ko dau
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string convertToUnSign(string s)
        {
            var regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
            string temp = s.Normalize(NormalizationForm.FormD);
            return regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
        }


        public static string DisplayAsMoney(string number)
        {
            number = number.Trim();
            var stack = new Stack();

            const int chunkSize = 3;
            try
            {
                for (int i = number.Length; i > 0; i -= chunkSize)
                {
                    if (i == 1)
                    {
                        stack.Push(number[0]);
                    }
                    else
                    {
                        stack.Push(number.Substring(i - chunkSize, chunkSize));
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLog(LogLevel.ERROR, ex + "\n" + ex.StackTrace);
            }

            string temp = string.Join(".", (from object v in stack select v.ToString()).ToArray());
            return temp;
        }

        public static void ShowAlert(string message)
        {
            // Cleans the message to allow single quotation marks 
            string cleanMessage = message.Replace("'", "\\'");
            string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

            // Gets the executing web page 
            var page = HttpContext.Current.CurrentHandler as Page;

            // Checks if the handler is a Page and that the script isn't allready on the Page 
            if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
            {
                page.ClientScript.RegisterClientScriptBlock(typeof (Common), "alert", script);
            }
        }

        public static bool CheckisActiveSite()
        {
            return Global.isActiveSite;
        }

        public static void DeActiveOrActiveSite(bool flag)
        {
            Global.isActiveSite = flag;
        }

        public static string CheckLinkPhoto(string imgPath)
        {
            string imgPathReturn;
            imgPathReturn = string.IsNullOrEmpty(imgPath) ? @"/images/imageNotAvailable.jpg" : imgPath;
            return imgPathReturn;
        }

        public static void SendEmail(string To, string Subject, string Body, bool isGmail)
        {
            try
            {
                string MailFrom = ConfigurationSettings.AppSettings["MailFrom"];
                 string MailServer = ConfigurationSettings.AppSettings["MailServer"];
                 string MailA_User = ConfigurationSettings.AppSettings["MailA_User"];
                string MailA_Pass = ConfigurationSettings.AppSettings["MailA_Pass"];
                 int MailA_Port = int.Parse(ConfigurationSettings.AppSettings["Port"]);

                MailMessage message = new MailMessage(MailFrom, To, Subject, Body);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.IsBodyHtml = true;
                //++20101103: PhuongHD add code: fix send mail 
                if (isGmail)
                {
                    //Gmail use SSL on port 587 or 465
                    SmtpClient emailClient = new SmtpClient(MailServer, MailA_Port);
                    System.Net.NetworkCredential SMTPUserInfo =
                        new System.Net.NetworkCredential(MailA_User, MailA_Pass);
                    emailClient.EnableSsl = true;
                    emailClient.UseDefaultCredentials = false;
                    emailClient.Credentials = SMTPUserInfo;
                    emailClient.Send(message);
                }
                else // send using IIS
                {
                    SmtpClient emailClient = new SmtpClient();
                    emailClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
                    System.Net.NetworkCredential SMTPUserInfo =
                        new System.Net.NetworkCredential(MailA_User, MailA_Pass);
                    emailClient.UseDefaultCredentials = false;
                    emailClient.Credentials = SMTPUserInfo;
                    emailClient.Send(message);
                }
               

            }
            catch (Exception ex)
            {
               Logger.WriteLog(LogLevel.ERROR, ex+"\n"+ex.StackTrace);
            }

        }
    }
}